package com.h3bpm.kumhosunny.crm.controller.budget;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataRow;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @authormi
 * @date2019/9/10
 */
@Controller
@RequestMapping("/Portal/CRM/BudgetLock")
public class BudgetLockController extends ControllerBase {

    private static final Logger LOGGER = LoggerFactory.getLogger(ControllerBase.class);

    private static String UNDERWAY="2";

    private static String REJECT="3";

    private static String COMPLETE="4";



    @Override
    public String getFunctionCode() {
        return null;
    }
    /**
     *
     * @param instanceId
     * @param state
     *  2.占用(占用预算金额);4.通过(锁定预算金额);3.驳回预算金额
     * @return
     */
    @RequestMapping("/occupationDubgetDetailManage")
    @ResponseBody
    public JSONObject occupationDubgetDetailManage(String instanceId,String state){

         if(UNDERWAY.equals(state)){
             JSONObject result = approvalOccupationDubget(instanceId);
             return result;
         }else if(REJECT.equals(state)){
             JSONObject result = rejectDubgetEvection(instanceId);
             return result;
         }else if(COMPLETE.equals(state)){
             JSONObject result = lockDubget(instanceId);
             return result;
         }
        JSONObject result = new JSONObject();
         result.put("status","200");
         result.put("message","请提交要操作预算金额的状态代码");
         return result;

    }


    /**
     * 出差申请金额占用预算
     * @param instanceId
     * @return
     */
    public JSONObject approvalOccupationDubget(String instanceId){

        JSONObject result =new JSONObject();
        result.put("status","200");
        result.put("message","提交申请预算占用成功");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       try{
          InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
          //申请人id
          String  applicantId = instanceData.getBizObject().getCreatedBy();
          //申请金额
          String  appliedAmount = instanceData.getBizObject().GetValue("amountCost").toString();
          //获取预计出差时间
          String dateTravel =  simpleDateFormat.format(instanceData.getBizObject().GetValue("startTime"));
          String[] dateStr = dateTravel.split("-");
          String  year =dateStr[0];
          String month = dateStr[1];
          String getDubgetSql = "select * from k_dubgetexpand where userId = '"+applicantId+"' and byear='"+year+"' and  bmonth='"+month+"'";
          DataTable dataDubget =  SqlUtil.doQuery(getDubgetSql);
          if(dataDubget!=null && dataDubget.getEntityRows()!=null && dataDubget.getEntityRows().size()>0){
              DataRow dataRow = dataDubget.getEntityRows().get(0);
              //判断如果申请金额大于预算金额
             // if(new BigDecimal(dataRow.getString("availableBudget")).compareTo( new BigDecimal(appliedAmount))> -1){

                  //可用预算减去出差申请金额
                  BigDecimal  availableBudget = dataRow.getBigDecimal("availableBudget").subtract( new BigDecimal(appliedAmount));

                  //预算占用金额加上出差申请金额
                  BigDecimal  occupationBudget = dataRow.getBigDecimal("occupationBudget").add(new BigDecimal(appliedAmount));

                  //写入预算占用
                  String updateDubgetSql = "update k_dubgetexpand set  ModifiedBy = '"+applicantId+"' ,ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"' , occupationBudget ='"+occupationBudget+"' , availableBudget= '"+availableBudget+"' where objectId ='"+dataRow.getString("objectId")+"'";
                  SqlUtil.doNoQuery(updateDubgetSql);

                  //写入预算占用明细表
                  String objectId = UUID.randomUUID().toString();
                  String kBudgetAppSchInsertSql = " insert into  k_budget_appropriation_schedule(objectId,businessTravelRequestId,applicantId,appliedAmount,status,CreatedTime,CreatedBy,ModifiedTime,ModifiedBy,dateTravel) values ";
                  String kBudgetAppSchInsertValue="('"+objectId+"','"+instanceId+"','"+applicantId+"','"+new BigDecimal(appliedAmount)+"','2','"+simpleDateFormatUpdate.format(new Date())+"','"+applicantId+"','"+simpleDateFormatUpdate.format(new Date())+"','"+applicantId+"','"+dateTravel+"')";
                  SqlUtil.doNoQuery(kBudgetAppSchInsertSql+kBudgetAppSchInsertValue);
                  BudgetSumSoloController.updatePracticalAvailableBudget(dateTravel,applicantId);
                  result.put("status","200");
                  result.put("message","出差金额申请占用预算金额成功");

                  return result;



          }else{
              result.put("status","500");
              result.put("message","此人没有可用预算记录");
              return result;
          }
       }catch (Exception e){
           result.put("status","500");
           result.put("message","系统异常");
           LOGGER.error("系统异常");
           e.printStackTrace();
       }

        return result;
    }


    /**
     *预算驳回
     * @param instanceId
     * @return
     */
    public JSONObject rejectDubgetEvection(String instanceId) {

        JSONObject result =new JSONObject();
        result.put("status","200");
        result.put("message","出差金额申请释放占用预算金额成功");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
            //申请人id
            String  applicantId = instanceData.getBizObject().getCreatedBy();
            //申请金额
            String  appliedAmount = instanceData.getBizObject().GetValue("amountCost").toString();
            //获取预计出差时间
            String dateTravel =  simpleDateFormat.format(instanceData.getBizObject().GetValue("startTime"));
            String[] dateStr = dateTravel.split("-");
            String  year =dateStr[0];
            String month = dateStr[1];
            String getDubgetSql = "select * from k_dubgetexpand where userId = '"+applicantId+"' and byear='"+year+"' and  bmonth='"+month+"'";
            DataTable dataDubget =  SqlUtil.doQuery(getDubgetSql);
            DataRow dataRow = dataDubget.getEntityRows().get(0);

                    //可用预算加上出差申请金额
                    BigDecimal  availableBudget = dataRow.getBigDecimal("availableBudget").add(new BigDecimal(appliedAmount));
                    //预算占用金额减去出差申请金额
                    BigDecimal  occupationBudget = dataRow.getBigDecimal("occupationBudget").subtract(new BigDecimal(appliedAmount));

                    //预算拓展表释放
                    String updateDubgetSql = "update k_dubgetexpand set  ModifiedBy = '"+applicantId+"' ,ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"' , occupationBudget ='"+occupationBudget+"' , availableBudget= '"+availableBudget+"' where objectId ='"+dataRow.getString("objectId")+"'";
                    SqlUtil.doNoQuery(updateDubgetSql);

                    //作废预算占用明细表记录
                    String updateDubgetDel = "update k_budget_appropriation_schedule  set  ModifiedBy = '"+applicantId+"',ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"',status ='0'   where businessTravelRequestId = '"+instanceId+"' and  status ='2'";
                    SqlUtil.doNoQuery(updateDubgetDel);
            BudgetSumSoloController.updatePracticalAvailableBudget(dateTravel,applicantId);
                    result.put("status","200");
                    result.put("message","出差金额申请释放占用预算金额成功");
                    return result;
        }catch (Exception e){
            result.put("status","500");
            result.put("message","系统异常");
            LOGGER.error("系统异常");
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 锁定预算
     * @param instanceId
     * @return
     */
    public JSONObject lockDubget(String instanceId){
        JSONObject result =new JSONObject();
        result.put("status","200");
        result.put("message","出差金额申请锁定成功");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
            //申请人id
            String  applicantId = instanceData.getBizObject().getCreatedBy();
            //申请金额
            String  appliedAmount = instanceData.getBizObject().GetValue("amountCost").toString();
            //获取预计出差时间
            String dateTravel =  simpleDateFormat.format(instanceData.getBizObject().GetValue("startTime"));
            String[] dateStr = dateTravel.split("-");
            String  year =dateStr[0];
            String month = dateStr[1];
            String getDubgetSql = "select * from k_dubgetexpand where userId = '"+applicantId+"' and byear='"+year+"' and  bmonth='"+month+"'";
            DataTable dataDubget =  SqlUtil.doQuery(getDubgetSql);
            DataRow dataRow = dataDubget.getEntityRows().get(0);

            //预算占用金额减去出差申请金额
            BigDecimal  occupationBudget = dataRow.getBigDecimal("occupationBudget").subtract(new BigDecimal(appliedAmount));
            //锁定金额加上出差金额
            BigDecimal  lockBudget =  dataRow.getBigDecimal("lockBudget").add(new BigDecimal(appliedAmount));


            //预算拓展表释放
            String updateDubgetSql = "update k_dubgetexpand set  ModifiedBy = '"+applicantId+"' ,ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"' , occupationBudget ='"+occupationBudget+"' , lockBudget= '"+lockBudget+"' where objectId ='"+dataRow.getString("objectId")+"'";
            SqlUtil.doNoQuery(updateDubgetSql);


            //修改预算占用明细表
            String updateDubgetDel = "update k_budget_appropriation_schedule  set  ModifiedBy = '"+applicantId+"',ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"',status ='4'   where businessTravelRequestId = '"+instanceId+"' and  status ='2'";
            SqlUtil.doNoQuery(updateDubgetDel);
            BudgetSumSoloController.updatePracticalAvailableBudget(dateTravel,applicantId);
            result.put("status","200");
            result.put("message","出差金额申请锁定成功");
            return result;
        }catch (Exception e){
            result.put("status","500");
            result.put("message","系统异常");
            LOGGER.error("系统异常");
            e.printStackTrace();
        }
        return result;


    }


    /**
     *招待费用申请预算逻辑
     * @param instanceId
     * @param state
     *  2.占用(占用预算金额);4.通过(锁定预算金额);3.驳回预算金额
     * @return
     */
    @RequestMapping("/entertainmentDubgetDetailManage")
    @ResponseBody
    public JSONObject entertainmentDubgetDetailManage(String instanceId,String state){

        if(UNDERWAY.equals(state)){
            JSONObject result = entertainmentDubget(instanceId);
            return result;
        }else if(REJECT.equals(state)){
            JSONObject result = rejectDubgetEntertainment(instanceId);
            return result;
        }else if(COMPLETE.equals(state)){
            JSONObject result = lockDubgetEntertainment(instanceId);
            return result;
        }
        JSONObject result = new JSONObject();
        result.put("status","200");
        result.put("message","请提交要操作预算金额的状态代码");
        return result;

    }




    /**
     * 招待费用申请占用预算
     * @param instanceId
     * @return
     */
    public JSONObject  entertainmentDubget(String instanceId){

        JSONObject result =new JSONObject();
        result.put("status","200");
        result.put("message","提交申请预算占用成功");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
            //申请人id
            String  applicantId = instanceData.getBizObject().getCreatedBy();
            //申请金额
            String  appliedAmount = instanceData.getBizObject().GetValue("sumMoney").toString();
            //获取招待费提交时间
            String dateTravel =  simpleDateFormat.format(instanceData.getInstanceContext().getStartTime());
            String[] dateStr = dateTravel.split("-");
            String  year =dateStr[0];
            String month = dateStr[1];
            String getDubgetSql = "select * from k_dubgetexpand where userId = '"+applicantId+"' and byear='"+year+"' and  bmonth='"+month+"'";
            DataTable dataDubget =  SqlUtil.doQuery(getDubgetSql);
            if(dataDubget!=null && dataDubget.getEntityRows()!=null && dataDubget.getEntityRows().size()>0){
                DataRow dataRow = dataDubget.getEntityRows().get(0);
                //判断如果申请金额大于预算金额
               // if(new BigDecimal(dataRow.getString("dyMonthBudget")).compareTo( new BigDecimal(appliedAmount))> -1){

                    //可用预算减去出差申请金额
                    BigDecimal  availableBudget = dataRow.getBigDecimal("availableBudget").subtract( new BigDecimal(appliedAmount));

                    //预算占用金额加上出差申请金额
                    BigDecimal  occupationBudget = dataRow.getBigDecimal("occupationBudget").add(new BigDecimal(appliedAmount));

                    //写入预算占用
                    String updateDubgetSql = "update k_dubgetexpand set  ModifiedBy = '"+applicantId+"' ,ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"' , occupationBudget ='"+occupationBudget+"' , availableBudget= '"+availableBudget+"' where objectId ='"+dataRow.getString("objectId")+"'";
                    SqlUtil.doNoQuery(updateDubgetSql);

                    //写入预算占用明细表
                    String objectId = UUID.randomUUID().toString();
                    String kBudgetAppSchInsertSql = " insert into  k_budget_appropriation_schedule(objectId,businessTravelRequestId,applicantId,appliedAmount,status,CreatedTime,CreatedBy,ModifiedTime,ModifiedBy,dateTravel) values ";
                    String kBudgetAppSchInsertValue="('"+objectId+"','"+instanceId+"','"+applicantId+"','"+new BigDecimal(appliedAmount)+"','2','"+simpleDateFormatUpdate.format(new Date())+"','"+applicantId+"','"+simpleDateFormatUpdate.format(new Date())+"','"+applicantId+"','"+dateTravel+"')";
                    SqlUtil.doNoQuery(kBudgetAppSchInsertSql+kBudgetAppSchInsertValue);
                    BudgetSumSoloController.updatePracticalAvailableBudget(dateTravel,applicantId);
                    result.put("status","200");
                    result.put("message","招待费用申请占用预算金额成功");
                    return result;


            }else{
                result.put("status","500");
                result.put("message","此人没有可用预算记录");
                return result;
            }
        }catch (Exception e){
            result.put("status","500");
            result.put("message","系统异常");
            LOGGER.error("系统异常");
            e.printStackTrace();
        }

        return result;
    }


    /**
     *招待费用申请  预算驳回
     * @param instanceId
     * @return
     */
    public JSONObject rejectDubgetEntertainment(String instanceId) {

        JSONObject result =new JSONObject();
        result.put("status","200");
        result.put("message","招待费用申请释放占用预算金额成功");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
            //申请人id
            String  applicantId = instanceData.getBizObject().getCreatedBy();
            //申请金额
            String  appliedAmount = instanceData.getBizObject().GetValue("sumMoney").toString();
            //获取预计出差时间
            String dateTravel =  simpleDateFormat.format(instanceData.getInstanceContext().getStartTime());
            String[] dateStr = dateTravel.split("-");
            String  year =dateStr[0];
            String month = dateStr[1];
            String getDubgetSql = "select * from k_dubgetexpand where userId = '"+applicantId+"' and byear='"+year+"' and  bmonth='"+month+"'";
            DataTable dataDubget =  SqlUtil.doQuery(getDubgetSql);
            DataRow dataRow = dataDubget.getEntityRows().get(0);

            //可用预算加上出差申请金额
            BigDecimal  availableBudget = dataRow.getBigDecimal("availableBudget").add(new BigDecimal(appliedAmount));
            //预算占用金额减去出差申请金额
            BigDecimal  occupationBudget = dataRow.getBigDecimal("occupationBudget").subtract(new BigDecimal(appliedAmount));

            //预算拓展表释放
            String updateDubgetSql = "update k_dubgetexpand set  ModifiedBy = '"+applicantId+"' ,ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"' , occupationBudget ='"+occupationBudget+"' , availableBudget= '"+availableBudget+"' where objectId ='"+dataRow.getString("objectId")+"'";
            SqlUtil.doNoQuery(updateDubgetSql);

            //作废预算占用明细表记录
            String updateDubgetDel = "update k_budget_appropriation_schedule  set  ModifiedBy = '"+applicantId+"',ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"',status ='0'   where businessTravelRequestId = '"+instanceId+"' and  status ='2'";
            SqlUtil.doNoQuery(updateDubgetDel);
            BudgetSumSoloController.updatePracticalAvailableBudget(dateTravel,applicantId);
            result.put("status","200");
            result.put("message","招待费用申请释放占用预算金额成功");
            return result;
        }catch (Exception e){
            result.put("status","500");
            result.put("message","系统异常");
            LOGGER.error("系统异常");
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 招待费用申请锁定预算
     * @param instanceId
     * @return
     */
    public JSONObject lockDubgetEntertainment(String instanceId){
        JSONObject result =new JSONObject();
        result.put("status","200");
        result.put("message","招待费用申请锁定成功");
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormatUpdate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            InstanceData instanceData = new InstanceData(getEngine(),instanceId, User.AdministratorID);
            //申请人id
            String  applicantId = instanceData.getBizObject().getCreatedBy();
            //申请金额
            String  appliedAmount = instanceData.getBizObject().GetValue("sumMoney").toString();
            //获取预计出差时间
            String dateTravel =  simpleDateFormat.format(instanceData.getInstanceContext().getStartTime());
            String[] dateStr = dateTravel.split("-");
            String  year =dateStr[0];
            String month = dateStr[1];
            String getDubgetSql = "select * from k_dubgetexpand where userId = '"+applicantId+"' and byear='"+year+"' and  bmonth='"+month+"'";
            DataTable dataDubget =  SqlUtil.doQuery(getDubgetSql);
            DataRow dataRow = dataDubget.getEntityRows().get(0);

            //预算占用金额减去出差申请金额
            BigDecimal  occupationBudget = dataRow.getBigDecimal("occupationBudget").subtract(new BigDecimal(appliedAmount));
            //锁定金额加上出差金额
            BigDecimal  lockBudget =  dataRow.getBigDecimal("lockBudget").add(new BigDecimal(appliedAmount));


            //预算拓展表释放
            String updateDubgetSql = "update k_dubgetexpand set  ModifiedBy = '"+applicantId+"' ,ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"' , occupationBudget ='"+occupationBudget+"' , lockBudget= '"+lockBudget+"' where objectId ='"+dataRow.getString("objectId")+"'";
            SqlUtil.doNoQuery(updateDubgetSql);


            //修改预算占用明细表
            String updateDubgetDel = "update k_budget_appropriation_schedule  set  ModifiedBy = '"+applicantId+"',ModifiedTime='"+simpleDateFormatUpdate.format(new Date())+"',status ='4'   where businessTravelRequestId = '"+instanceId+"' and  status ='2'";
            SqlUtil.doNoQuery(updateDubgetDel);
            BudgetSumSoloController.updatePracticalAvailableBudget(dateTravel,applicantId);
            result.put("status","200");
            result.put("message","招待费用申请锁定成功");
            return result;
        }catch (Exception e){
            result.put("status","500");
            result.put("message","系统异常");
            LOGGER.error("系统异常");
            e.printStackTrace();
        }
        return result;


    }






}
